import { useStore } from '@/store';

function getMenuItems(routes) {
	return routes
		.filter((route = {}) => {
			const { hideMenu = false } = route.meta || {};
			return !hideMenu;
		}).map((route = {}) => {
			const { name, meta = {}, children } = route;
			const { icon, label } = meta;
			const result = { name, icon, label };
			if (Array.isArray(children)) {
				result.children = children.map(v => getMenuItems(v));
			}
			return result;
		});
}

async function initRoutes(modules) {
	const allModule = [];
	const store = useStore();
	for (let module of Object.values(modules)) {
		Object.values((await module())).forEach(item => {
			const { resourceList } = store.accountInfo || {};
			if (item && item.authKey === 'forcePass') {
				allModule.push(item);
			} else {
				if (!resourceList?.length) throw new Error('没有获取到菜单权限数据');
				if (resourceList.some(item => item.viewKey === item.authKey)) {
					allModule.push(item);
				}
			}
		});
	}

	const items = allModule.sort((item1, item2) => {
		return item1.sort - item2.sort;
	});
	const menus = items
		.filter(({ hideMenu = false }) => !hideMenu)
		.map(({ name, label, icon, routes }) => {
			return { name, label, icon, children: getMenuItems(routes) };
		});
	// 等待pinia挂载完毕后再使用
	setTimeout(() => store.setMenus(menus));
	return items.map(item => item.routes).flat(Infinity);
}

export default async function() {
	return {
		path: '/',
		name: 'Home',
		redirect: '/home',
		component: () => import('@/components/layouts/BasicLayout'),
		children: (await initRoutes(import.meta.glob('./modules/*.js'))),
	};
}